package com.dyzx.hbb.modules.mtn.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dyzx.hbb.common.base.PageQuery;
import com.dyzx.hbb.common.base.Result;
import com.dyzx.hbb.common.config.MyLambdaQueryWrapper;
import com.dyzx.hbb.common.controller.BaseCustomListController;
import com.dyzx.hbb.common.utils.Utils;
import com.dyzx.hbb.common.utils.ValidUtils;
import com.dyzx.hbb.modules.mtn.entity.MtnCarVehicle;
import com.dyzx.hbb.modules.mtn.entity.MtnOrder;
import com.dyzx.hbb.modules.mtn.entity.MtnOrderItem;
import com.dyzx.hbb.modules.mtn.query.MtnOrderQuery;
import com.dyzx.hbb.modules.mtn.service.MtnCarVehicleService;
import com.dyzx.hbb.modules.mtn.service.MtnOrderItemService;
import com.dyzx.hbb.modules.mtn.service.MtnOrderService;
import com.dyzx.hbb.modules.mtn.vo.MtnOrderItemStatusVO;
import com.dyzx.hbb.modules.mtn.vo.MtnOrderItemVO;
import com.dyzx.hbb.modules.sys.entity.SysWorkFlow;
import com.dyzx.hbb.modules.sys.service.SysWorkFlowService;
import com.dyzx.hbb.modules.wms.entity.WmsProduct;
import com.dyzx.hbb.modules.wms.service.WmsProductService;
import com.dyzx.hbb.security.context.SecurityContextHolder;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 维修订单控制器
 * <p>处理维修模块中的订单管理，包括维修订单的创建、查询、更新和删除等核心业务操作
 * <p>主要职责：
 * <ul>
 * <li>根据车辆VIN码创建维修订单</li>
 * <li>查询维修订单详情及关联的车辆、客户信息</li>
 * <li>管理订单项目（查询项目列表、保存项目、更新项目状态）</li>
 * <li>实现按条件查询维修订单列表</li>
 * <li>处理订单相关数据计算和验证</li>
 * </ul>
 * <p>设计意图：为维修服务提供完整的订单管理功能，
 * 支持从订单创建到项目管理的全流程业务处理
 * 
 * @author 开发团队
 * @version 1.0.0
 * @since 2023-05-30
 */
@Tag(name = "02.维修订单管理", description = "维修订单管理相关接口，包括订单的创建、查询、更新和删除等操作")
@RestController
@RequestMapping("/mtn/order")
public class MtnOrderController extends BaseCustomListController<MtnOrderService, MtnOrder, MtnOrderQuery> {
    @Autowired
    private MtnOrderService service;
    @Autowired
    private MtnCarVehicleService carVehicleService;

    @Autowired
    private MtnOrderItemService itemService;
    @Autowired
    private WmsProductService productService;

    @Autowired
    private SysWorkFlowService workFlowService;




    /**
     * 创建维修订单
     * @param vin 车辆识别码
     * @return 创建的订单信息
     */
    @Operation(summary = "创建维修订单", description = "根据车辆识别码(VIN)创建新的维修订单")
    @GetMapping("/create/{vin}")
    public Result<Map<String, Object>> create(@Parameter(description = "车辆识别码") @PathVariable String vin) {
        Long userId = SecurityContextHolder.getUserId();
        Long organId = SecurityContextHolder.getOrganId();
        MtnCarVehicle carVehicle = carVehicleService.getByVin(vin);
        if (carVehicle == null) {
            return Result.error("车辆不存在");

        }
        Map<String, Object> detailVin = getDetailVin(carVehicle.getId());
        if(detailVin != null){
            return Result.ok(detailVin);
        }
        MtnOrder order = new MtnOrder();
        String mtn = Utils.getOrderNum("MTN");
        order.setNo(mtn);
        order.setVehicleId(carVehicle.getId());
        //  order.setCustomerId(carVehicle.getCustomerId());
        order.setSalesmanId(userId);
        order.setOperatorId(userId);
        order.setOrganId(organId);
        boolean save = service.save(order);
        System.out.println("vin:" + vin);
        if (save) {
            Long id = order.getId();
            Map<String, Object> map = getDetail(id);
            return Result.ok(map);
        } else {
            return Result.error("创建失败");
        }

    }

    /**
     * 查询维修订单详情
     * @param id 订单ID
     * @return 订单详细信息
     */
    @Operation(summary = "查询维修订单详情", description = "根据订单ID查询维修订单的详细信息")
    @GetMapping("/{id}")
    public Result<Map<String, Object>> get(@Parameter(description = "订单ID") @PathVariable Long id) {
        Map<String, Object> map = getDetail(id);
        return map.isEmpty() ? Result.error(404, "暂无数据") : Result.ok(map);
    }

    /**
     * 获取订单详情
     * @param id 订单ID
     * @return 订单详情Map
     */
    private Map<String, Object> getDetail(Long id) {
MyLambdaQueryWrapper<MtnOrder> queryWrapper =getDetailWrapper();
        queryWrapper.eq(MtnOrder::getId, id);
        return service.getMap(queryWrapper);
    }

    private Map<String, Object> getDetailVin(Long vin) {
        MyLambdaQueryWrapper<MtnOrder> queryWrapper =getDetailWrapper();
        queryWrapper.eq(MtnOrder::getVehicleId, vin).eq(MtnOrder::getStatus, 1);
        return service.getMap(queryWrapper);
    }

    private MyLambdaQueryWrapper<MtnOrder> getDetailWrapper() {
        MyLambdaQueryWrapper<MtnOrder> queryWrapper = new MyLambdaQueryWrapper<>();

        queryWrapper.last("limit 1");
        queryWrapper.select(MtnOrder::getId, MtnOrder::getNo, MtnOrder::getVehicleId, MtnOrder::getCustomerId, MtnOrder::getSalesmanId, MtnOrder::getOperatorId, MtnOrder::getOrganId
                , MtnOrder::getExpectedOutTime, MtnOrder::getType, MtnOrder::getActualOutTime, MtnOrder::getTotalMileage, MtnOrder::getStatus, MtnOrder::getRemark, MtnOrder::getIsPaid, MtnOrder::getTotalAmt, MtnOrder::getCreateDate, MtnOrder::getUpdateDate);

        queryWrapper.userName(MtnOrder::getSalesmanId).as("salesman_name");
        queryWrapper.userName(MtnOrder::getOperatorId).as("operator_name");
        queryWrapper.organName(MtnOrder::getOrganId).as("organ_name");
        queryWrapper.userName(MtnOrder::getCustomerId).as("customer_name");
        queryWrapper.select("(SELECT vin FROM mtn_car_vehicle WHERE id = vehicle_id LIMIT 1)").as("vehicle_name");
        // car_vehicle.car_modal_id
        queryWrapper.select("(SELECT model FROM car_model WHERE id in((SELECT car_modal_id FROM mtn_car_vehicle WHERE id = vehicle_id )) LIMIT 1)").as("car_modal_name");
        queryWrapper.select("(SELECT name FROM car_mark WHERE id in((SELECT car_mark_id FROM mtn_car_vehicle WHERE id = vehicle_id )) LIMIT 1)").as("car_mark_name");
        queryWrapper.select("(SELECT logo FROM car_model WHERE id in((SELECT car_modal_id FROM mtn_car_vehicle WHERE id = vehicle_id )) LIMIT 1)").as("car_modal_logo");

return queryWrapper;
    }

    /**
     * 查询订单项目列表
     * @param id 订单ID
     * @return 订单项目列表
     */
    @Operation(summary = "查询订单项目列表", description = "根据订单ID查询该订单下的所有项目")
    @GetMapping("/item/{id}")
    public Result<List<Map<String, Object>>> getItem(@Parameter(description = "订单ID") @PathVariable Long id) {
        List<Map<String, Object>> map = getDetailItems(id);
        return map.isEmpty() ? Result.error(404, "暂无数据") : Result.ok(map);
    }

    /**
     * 获取订单项目详情
     * @param id 订单ID
     * @return 订单项目详情列表
     */
    private List<Map<String, Object>> getDetailItems(Long id) {
        MyLambdaQueryWrapper<MtnOrderItem> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.eq(MtnOrderItem::getOrderId, id);
        //   queryWrapper.last("limit 1");
        queryWrapper.select(MtnOrderItem::getId, MtnOrderItem::getSalesmanId, MtnOrderItem::getOperatorId, MtnOrderItem::getOrganId
                , MtnOrderItem::getStatus, MtnOrderItem::getRemark, MtnOrderItem::getTotalAmt, MtnOrderItem::getCreateDate, MtnOrderItem::getUpdateDate);
        queryWrapper.select(MtnOrderItem::getProductId, MtnOrderItem::getWorkFlowId, MtnOrderItem::getPartsAmt, MtnOrderItem::getServiceHours, MtnOrderItem::getServiceTotalAmt,MtnOrderItem::getDiscountAmt,MtnOrderItem::getCommission, MtnOrderItem::getServiceAmt, MtnOrderItem::getTotalAmt);

        //  queryWrapper.userName(MtnOrderItemItem::getSalesmanId).as("salesman_name");
        queryWrapper.select("(SELECT name FROM sys_work_flow WHERE id = work_flow_id LIMIT 1)").as("work_flow_name");
        queryWrapper.select("(SELECT name FROM wms_product WHERE id = product_id LIMIT 1)").as("product_name");
        queryWrapper.userName(MtnOrderItem::getOperatorId).as("operator_name");
        queryWrapper.organName(MtnOrderItem::getOrganId).as("organ_name");

        return itemService.listMaps(queryWrapper);
    }

    /**
     * 保存订单项目
     * @param item 订单项目VO
     * @return 保存结果
     */
    @Operation(summary = "保存订单项目", description = "添加新的订单项目到维修订单")
    @PostMapping("/item")
    public Result<Boolean> saveItem(@Parameter(description = "订单项目信息") @Valid @RequestBody MtnOrderItemVO item) {
        Long userId = SecurityContextHolder.getUserId();
        Long organId = SecurityContextHolder.getOrganId();
        WmsProduct productById = productService.findById(item.getProductId());
        if (productById == null) {
            return Result.error("产品不存在");
        }
        SysWorkFlow workFlowById = workFlowService.getById(item.getWorkFlowId());
        if (workFlowById == null) {
            return Result.error("工单不存在");
        }
        MtnOrderItem orderItem = new MtnOrderItem();
        BeanUtil.copyProperties(item, orderItem);
        orderItem.setPartsAmt(productById.getAmt());
        orderItem.setServiceHours(workFlowById.getServiceHours());
        orderItem.setCommission(workFlowById.getCommission());
        orderItem.setServiceAmt(workFlowById.getServiceAmt());
        orderItem.setServiceTotalAmt(workFlowById.getCommission() + workFlowById.getServiceAmt());
        orderItem.setTotalAmt(getTotal(productById.getAmt(), workFlowById.getCommission(), workFlowById.getServiceAmt()));
        orderItem.setOperatorId(userId);
        orderItem.setOrganId(organId);
        boolean save = itemService.save(orderItem);
        if( save){
            List<MtnOrderItem> list = itemService.list(new MyLambdaQueryWrapper<MtnOrderItem>().eq(MtnOrderItem::getOrderId, item.getOrderId()));
            Long reduce = list.stream().map(MtnOrderItem::getTotalAmt).reduce(0L, Long::sum);
            Long discount = list.stream().map(item1 -> item1.getDiscountAmt() == null ? 0L : item1.getDiscountAmt()).reduce(0L, Long::sum);

            MtnOrder order = new MtnOrder();
            order.setId(item.getOrderId());
            order.setTotalAmt(reduce);
            order.setDiscountAmt(discount);
         service.updateById(order);
        }
        return save ? Result.ok() : Result.error("保存失败");
    }

    /**
     * 更新订单项目状态
     * @param item 订单项目状态VO
     * @return 更新结果
     * @see MtnOrderItemStatusVO 工单状态（0-待接车；1-维修中；2-待结算；3-已完成；4-已取消）
     */
    @Operation(summary = "更新订单项目状态", description = "更新订单项目的状态")
    @PutMapping("/item/status")
    public Result<Boolean> updateItemStatus(
           @Parameter(description = "订单项目状态信息") @Valid @RequestBody MtnOrderItemStatusVO item
    ) {
        if (item.getStatus() == 0 || item.getStatus() == 1 || item.getStatus() == 2 || item.getStatus() == 3 || item.getStatus() == 4) {
            MtnOrderItem byId = itemService.getById(item.getId());
            if(byId == null){
                return Result.error("工单不存在");
            }
            byId.setStatus(item.getStatus());
            boolean update = itemService.updateById(byId);
            return update ? Result.ok() : Result.error("保存失败");
        }
        Long userId = SecurityContextHolder.getUserId();
        return Result.error("状态错误");
    }

    /**
     * 计算总金额
     * @param amt 金额1
     * @param commission 佣金
     * @param amt1 金额2
     * @return 总金额
     */
    private Long getTotal(Long amt, Long commission, Long amt1) {
        long total = 0L;
        if (amt != null) {
            total += amt;
        }
        if (commission != null) {
            total += commission;
        }
        if (amt1 != null) {
            total += amt1;
        }
        return total;
    }

    /**
     * 获取基础服务类
     * @return 订单服务类实例
     */
    @Override
    protected MtnOrderService getBaseService() {
        return service;
    }

    /**
     * 构建查询条件包装器
     * @param query 查询参数
     * @return 查询条件包装器
     */
    @Override
    protected MyLambdaQueryWrapper<MtnOrder> queryWrapper(MtnOrderQuery query) {
        System.out.println("query = " + query);
        MyLambdaQueryWrapper<MtnOrder> queryWrapper = new MyLambdaQueryWrapper<>();

        queryWrapper.select(MtnOrder::getId, MtnOrder::getNo, MtnOrder::getVehicleId, MtnOrder::getCustomerId, MtnOrder::getSalesmanId, MtnOrder::getOperatorId, MtnOrder::getOrganId
                , MtnOrder::getExpectedOutTime, MtnOrder::getType, MtnOrder::getActualOutTime, MtnOrder::getTotalMileage, MtnOrder::getStatus, MtnOrder::getRemark, MtnOrder::getIsPaid, MtnOrder::getTotalAmt, MtnOrder::getCreateDate, MtnOrder::getUpdateDate);

        queryWrapper.userName(MtnOrder::getSalesmanId).as("salesman_name");
        queryWrapper.userName(MtnOrder::getOperatorId).as("operator_name");
        queryWrapper.organName(MtnOrder::getOrganId).as("organ_name");
        queryWrapper.userName(MtnOrder::getCustomerId).as("customer_name");
        queryWrapper.select("(SELECT vin FROM mtn_car_vehicle WHERE id = vehicle_id LIMIT 1)").as("vehicle_name");
   // car_vehicle.car_modal_id
        queryWrapper.select("(SELECT model FROM car_model WHERE id in((SELECT car_modal_id FROM mtn_car_vehicle WHERE id = vehicle_id )) LIMIT 1)").as("car_modal_name");
        queryWrapper.select("(SELECT name FROM car_mark WHERE id in((SELECT car_mark_id FROM mtn_car_vehicle WHERE id = vehicle_id )) LIMIT 1)").as("car_mark_name");
        queryWrapper.select("(SELECT logo FROM car_model WHERE id in((SELECT car_modal_id FROM mtn_car_vehicle WHERE id = vehicle_id )) LIMIT 1)").as("car_modal_logo");
queryWrapper.orderByAsc(MtnOrder::getStatus, MtnOrder::getCreateDate, MtnOrder::getId);
       if(query!=null){
           if(StringUtils.isNotEmpty(query.getSearch())){
               queryWrapper.inSql(ValidUtils.isValidVin(query.getSearch()),MtnOrder::getVehicleId, "(SELECT id FROM mtn_car_vehicle WHERE vin like '%"+query.getSearch()+"%')");
           //    queryWrapper.inSql(ValidUtils.isValidLicensePlate(query.getSearch()),MtnOrder::getVehicleId, "(SELECT id FROM mtn_car_vehicle WHERE license_plate like '%"+query.getSearch()+"%')
               queryWrapper.inSql(ValidUtils.isValidPhone(query.getSearch()),MtnOrder::getCustomerId, "(SELECT id FROM sys_user WHERE phone like '%"+query.getSearch()+"%')");
               queryWrapper.inSql(ValidUtils.isValidCardName(query.getSearch()),MtnOrder::getCustomerId, "(SELECT id FROM sys_user WHERE name like '%"+query.getSearch()+"%')");

               System.out.println("query.getSearch() = " + query.getSearch());
           }

           queryWrapper.eq(query.getType() != null, MtnOrder::getType, query.getType())
           .eq(query.getStatus() != null, MtnOrder::getStatus, query.getStatus())
            .eq(query.getIsPaid() != null, MtnOrder::getIsPaid, query.getIsPaid());
       }

        return queryWrapper;
    }
}
